/**
 * 移动端动态菜单权限管理器
 * @author Wu.Liang
 * @date 2025-01-30
 * @updated 2025-01-30 - 添加动态tabBar配置功能
 * @updated 2025-01-30 - 完善菜单权限配置，添加更多功能模块
 */

import { useAuthStore, useUserStore } from '@/store'

// 移动端菜单权限配置
export const MOBILE_MENU_PERMISSIONS = {
  // 第一层级 - 底部导航栏
  HOME: {
    code: 'mobile:home:menu',
    name: '首页',
    path: '/pages/index/index',
    icon: 'home',
    tabBar: true,
    iconPath: 'static/icons/home.png',
    selectedIconPath: 'static/icons/home-active.png'
  },
  SERVICES: {
    code: 'mobile:services:menu',
    name: '服务',
    path: '/pages/services/services',
    icon: 'service',
    tabBar: true,
    iconPath: 'static/icons/service.png',
    selectedIconPath: 'static/icons/service-active.png'
  },
  PROFILE: {
    code: 'mobile:profile:menu',
    name: '我的',
    path: '/pages/profile/index',
    icon: 'profile',
    tabBar: true,
    iconPath: 'static/icons/profile.png',
    selectedIconPath: 'static/icons/profile-active.png'
  },

  // 第二层级 - 主要功能模块
  SECURITY: {
    code: 'mobile:security:menu',
    name: '安防管理',
    path: '/pages/security/security',
    icon: 'shield',
    parentCode: 'mobile:home:menu',
    children: [
      {
        code: 'mobile:security:visitor:menu',
        name: '访客管理',
        path: '/pages/security/visitor',
        icon: 'user'
      }
    ]
  },
  PROPERTY: {
    code: 'mobile:property:menu',
    name: '物业服务',
    path: '/pages/property/property',
    icon: 'home',
    parentCode: 'mobile:home:menu',
    children: [
      {
        code: 'mobile:property:repair:menu',
        name: '报修服务',
        path: '/pages/property/repair',
        icon: 'tools'
      },
      {
        code: 'mobile:property:company:register:menu',
        name: '物业公司注册',
        path: '/pages/property/company-register',
        icon: 'building'
      }
    ]
  },
  PARKING: {
    code: 'mobile:parking:menu',
    name: '停车管理',
    path: '/pages/parking/parking',
    icon: 'car',
    parentCode: 'mobile:home:menu',
    children: [
      {
        code: 'mobile:parking:record:menu',
        name: '停车记录',
        path: '/pages/parking/record',
        icon: 'list'
      }
    ]
  },
  EMERGENCY: {
    code: 'mobile:emergency:menu',
    name: '紧急求助',
    path: '/pages/emergency/emergency',
    icon: 'warning',
    parentCode: 'mobile:home:menu',
    children: [
      {
        code: 'mobile:emergency:contact:menu',
        name: '紧急联系人',
        path: '/pages/emergency/contact',
        icon: 'phone'
      }
    ]
  },
  COMPLAINT: {
    code: 'mobile:complaint:menu',
    name: '投诉建议',
    path: '/pages/complaint/complaint',
    icon: 'chat',
    parentCode: 'mobile:home:menu'
  },
  PAYMENT: {
    code: 'mobile:payment:menu',
    name: '在线支付',
    path: '/pages/payment/payment',
    icon: 'credit-card',
    parentCode: 'mobile:home:menu',
    children: [
      {
        code: 'mobile:payment:list:menu',
        name: '支付记录',
        path: '/pages/payment/list',
        icon: 'list'
      },
      {
        code: 'mobile:payment:detail:menu',
        name: '支付详情',
        path: '/pages/payment/detail',
        icon: 'detail'
      },
      {
        code: 'mobile:payment:invoice:menu',
        name: '电子发票',
        path: '/pages/payment/invoice',
        icon: 'file'
      }
    ]
  },

  // 个人中心功能模块
  PROFILE_ACCOUNT: {
    code: 'mobile:profile:account:menu',
    name: '账户管理',
    path: '/pages/profile/account',
    icon: 'user',
    parentCode: 'mobile:profile:menu',
    children: [
      {
        code: 'mobile:profile:edit:menu',
        name: '编辑资料',
        path: '/pages/profile/edit',
        icon: 'edit'
      },
      {
        code: 'mobile:profile:change-password:menu',
        name: '修改密码',
        path: '/pages/profile/change-password',
        icon: 'lock'
      }
    ]
  },
  PROFILE_SECURITY: {
    code: 'mobile:profile:security:menu',
    name: '安全设置',
    path: '/pages/profile/security',
    icon: 'shield',
    parentCode: 'mobile:profile:menu'
  },
  PROFILE_NOTIFICATION: {
    code: 'mobile:profile:notification:menu',
    name: '消息通知',
    path: '/pages/profile/notification',
    icon: 'bell',
    parentCode: 'mobile:profile:menu'
  },
  PROFILE_ABOUT: {
    code: 'mobile:profile:about:menu',
    name: '关于我们',
    path: '/pages/profile/about',
    icon: 'info',
    parentCode: 'mobile:profile:menu'
  }
}

// 菜单权限管理器
export class MobileMenuPermissionManager {
  getUserPermissions() {
    const authStore = useAuthStore()
    const userStore = useUserStore()
    
    let permissions = authStore.permissions || []
    if (!permissions || permissions.length === 0) {
      permissions = userStore.userPermissions || []
    }
    
    return permissions
  }

  hasMenuPermission(menuCode) {
    // 暂时允许所有用户访问所有菜单
    // TODO: 后续根据具体需求设置权限控制
    console.log('菜单权限管理器: 暂时允许访问所有菜单', menuCode)
    return true
  }

  getAuthorizedMenus(parentCode = null) {
    const authorizedMenus = []
    
    Object.values(MOBILE_MENU_PERMISSIONS).forEach(menu => {
      if (parentCode && menu.parentCode !== parentCode) {
        return
      }
      
      if (this.hasMenuPermission(menu.code)) {
        const authorizedMenu = { ...menu }
        
        // 处理子菜单权限
        if (menu.children && menu.children.length > 0) {
          authorizedMenu.children = menu.children.filter(child => 
            this.hasMenuPermission(child.code)
          )
        }
        
        authorizedMenus.push(authorizedMenu)
      }
    })
    
    return authorizedMenus
  }

  getHomeFunctionMenus() {
    return this.getAuthorizedMenus('mobile:home:menu')
  }

  getProfileMenus() {
    return this.getAuthorizedMenus('mobile:profile:menu')
  }

  getServicesMenus() {
    return this.getAuthorizedMenus('mobile:services:menu')
  }

  /**
   * 获取动态tabBar配置
   * @returns {Array} tabBar配置列表
   */
  getDynamicTabBarConfig() {
    const tabBarMenus = [
      MOBILE_MENU_PERMISSIONS.HOME,
      MOBILE_MENU_PERMISSIONS.SERVICES,
      MOBILE_MENU_PERMISSIONS.PROFILE
    ]
    
    // 过滤有权限的tabBar菜单
    const authorizedTabBarMenus = tabBarMenus.filter(menu => this.hasMenuPermission(menu.code))
    
    // 转换为tabBar配置格式，移除前导斜杠以与pages.json保持一致
    return authorizedTabBarMenus.map(menu => ({
      pagePath: menu.path.startsWith('/') ? menu.path.slice(1) : menu.path,
      text: menu.name,
      iconPath: menu.iconPath,
      selectedIconPath: menu.selectedIconPath
    }))
  }

  /**
   * 更新pages.json中的tabBar配置
   * @param {Object} pagesConfig pages.json配置对象
   * @returns {Object} 更新后的配置对象
   */
  updatePagesConfig(pagesConfig) {
    const dynamicTabBar = this.getDynamicTabBarConfig()
    
    // 如果没有任何tabBar权限，返回原配置
    if (dynamicTabBar.length === 0) {
      console.warn('用户没有任何tabBar权限，使用默认配置')
      return pagesConfig
    }
    
    // 更新tabBar配置
    const updatedConfig = {
      ...pagesConfig,
      tabBar: {
        ...pagesConfig.tabBar,
        list: dynamicTabBar
      }
    }
    
    console.log('动态tabBar配置已更新:', dynamicTabBar)
    return updatedConfig
  }

  /**
   * 检查页面是否有访问权限
   * @param {string} pagePath 页面路径
   * @returns {boolean} 是否有权限
   */
  hasPagePermission(pagePath) {
    // 白名单页面直接放行
    const whiteList = [
      '/pages/login/login',
      '/pages/register/register',
      '/pages/error/403',
      '/pages/error/404'
    ]
    
    if (whiteList.includes(pagePath)) {
      return true
    }
    
    // 查找页面对应的权限编码
    const menu = this.findMenuByPath(pagePath)
    
    if (!menu) {
      console.warn(`未找到页面权限配置: ${pagePath}`)
      return true // 未配置权限的页面默认允许访问
    }
    
    return this.hasMenuPermission(menu.code)
  }

  /**
   * 根据路径查找菜单配置
   * @param {string} pagePath 页面路径
   * @returns {Object|null} 菜单配置
   */
  findMenuByPath(pagePath) {
    // 查找主菜单
    const mainMenu = Object.values(MOBILE_MENU_PERMISSIONS).find(menu => 
      menu.path === pagePath
    )
    
    if (mainMenu) {
      return mainMenu
    }
    
    // 查找子菜单
    for (const menu of Object.values(MOBILE_MENU_PERMISSIONS)) {
      if (menu.children) {
        const childMenu = menu.children.find(child => child.path === pagePath)
        if (childMenu) {
          return childMenu
        }
      }
    }
    
    return null
  }

  /**
   * 获取所有有权限的页面路径
   * @returns {Array} 页面路径列表
   */
  getAuthorizedPagePaths() {
    const authorizedPaths = []
    
    Object.values(MOBILE_MENU_PERMISSIONS).forEach(menu => {
      if (this.hasMenuPermission(menu.code)) {
        authorizedPaths.push(menu.path)
        
        // 添加子菜单路径
        if (menu.children) {
          menu.children.forEach(child => {
            if (this.hasMenuPermission(child.code)) {
              authorizedPaths.push(child.path)
            }
          })
        }
      }
    })
    
    return authorizedPaths
  }

  /**
   * 获取菜单图标
   * @param {string} iconName 图标名称
   * @returns {string} 图标字符
   */
  getMenuIcon(iconName) {
    const iconMap = {
      home: '🏠',
      service: '🔧',
      profile: '👤',
      shield: '🛡️',
      car: '🚗',
      warning: '⚠️',
      chat: '💬',
      'credit-card': '💳',
      user: '👥',
      tools: '🔨',
      building: '🏢',
      list: '📋',
      phone: '📞',
      edit: '✏️',
      lock: '🔒',
      bell: '🔔',
      info: 'ℹ️',
      detail: '📄',
      file: '📁'
    }
    
    return iconMap[iconName] || '📱'
  }
}

// 创建实例
export const menuPermissionManager = new MobileMenuPermissionManager()

// 导出工具函数
export const hasMenuPermission = (menuCode) => {
  return menuPermissionManager.hasMenuPermission(menuCode)
}

export const getAuthorizedMenus = (parentCode) => {
  return menuPermissionManager.getAuthorizedMenus(parentCode)
}

export const getHomeFunctionMenus = () => {
  return menuPermissionManager.getHomeFunctionMenus()
}

export const getProfileMenus = () => {
  return menuPermissionManager.getProfileMenus()
}

export const getServicesMenus = () => {
  return menuPermissionManager.getServicesMenus()
}

export const getDynamicTabBarConfig = () => {
  return menuPermissionManager.getDynamicTabBarConfig()
}

export const updatePagesConfig = (pagesConfig) => {
  return menuPermissionManager.updatePagesConfig(pagesConfig)
}

export const hasPagePermission = (pagePath) => {
  return menuPermissionManager.hasPagePermission(pagePath)
}

export const getAuthorizedPagePaths = () => {
  return menuPermissionManager.getAuthorizedPagePaths()
}

export const getMenuIcon = (iconName) => {
  return menuPermissionManager.getMenuIcon(iconName)
}

export default menuPermissionManager
